import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../views/Login.vue'
import NotFound from '../views/NotFound.vue'
import NoPermission from '../views/NoPermission.vue'
import Mainbox from '../views/Mainbox.vue'
import ConfigRoutes from './config'
import useRouterStore from '../store/useRouterStore'
import useUserStore from '../store/useUserStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const routes = [
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/mainbox',
        name: 'mainbox',
        component: Mainbox
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    // 开始进度条
    NProgress.start()

    const { isGetterRouter } = useRouterStore()
    const { user } = useUserStore()
    // 判断是否需要登录权限
    if (to.path === '/login') {
        next()
        return
    }
    // 获取当前的token是否存在
    if (!user.role) {
        next('/login')
    } else {
        const { role: { rights } } = user
        // 动态配置路由
        if (!isGetterRouter) {
            configRouter(rights)
            next({
                path: to.fullPath
            })
        } else {
            next()
        }
    }
})

const configRouter = (rights) => {
    // 注意：可能上次退出过了，需要清除上个用户有权限的路由，移除mainbox这个父路由，所有子路由也会被移除
    router.removeRoute('mainbox')
    // 还得把父路由再创建出来，否则不能根据mainbox创建子路由了
    router.addRoute({
        path: '/mainbox',
        name: 'mainbox',
        component: Mainbox
    })
    const { changeRouter } = useRouterStore()
    ConfigRoutes.forEach(item => {
        console.log(item.path)
        let i = 0
        if (rights.includes(item.path)) {
            router.addRoute('mainbox', item)
        } else {
            router.addRoute('mainbox', {
                path: item.path,
                component: NoPermission
            })
        }
    })

    // 加重定向
    router.addRoute({
        path: '/mainbox',
        redirect: '/index'
    })
    router.addRoute('mainbox', {
        path: '/',
        redirect: '/index'
    })
    // 404匹配
    router.addRoute('mainbox', {
        path: '/:pathMatch(.*)*',
        name: 'not found',
        component: NotFound
    })

    // 改变状态为true
    changeRouter(true)
}

router.afterEach(() => {
    NProgress.done()
})

export default router